package com.fbs.wowo.manage.service.imp;

import com.fbs.wowo.exception.ErrorCode;
import com.fbs.wowo.exception.GivenNullParamException;
import com.fbs.wowo.exception.InputVerifyFailedException;
import com.fbs.wowo.exception.NoSuchDataException;
import com.fbs.wowo.manage.entity.AccountDetail;
import com.fbs.wowo.manage.entity.User;
import com.fbs.wowo.manage.mapper.AccountDetailMapper;
import com.fbs.wowo.manage.mapper.UserMapper;
import com.fbs.wowo.manage.service.UserService;
import com.fbs.wowo.manage.vo.UserAuth;
import com.fbs.wowo.util.rongcloud.RCUtils;
import com.fbs.wowo.works.service.WorksService;
import com.fbs.wowo.wx.entity.WxBinding;
import com.fbs.wowo.wx.mapper.WxBindingMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.Date;
import java.util.List;

/*******************************
 *
 * 用户增删改查操作
 *
 * TODO 获取用户信息返回数据删改，只取status正常的
 *
 *******************************/
@Service("userService")
@Transactional
public class UserServiceImp implements UserService {

    /**
     * 按id获取user
     * @param id
     * @return
     */
    @Override
    public User findById(String id) {
        return userMapper.selectByPrimaryKey(id);
    }

    /**
     * 修改user信息
     * @param user 传入userId 和 name，头像等信息用于修改
     */
    @Override
    public User modify(User user) throws GivenNullParamException, InputVerifyFailedException, NoSuchDataException {
        // TODO 判断是否本人操作
        if (user == null) throw new GivenNullParamException();
        User u = validateUser(user.getUserId());
        // 获取id
        user.setId(u.getId());
        // 新注册用户补全信息
        // 上传头像
        // 融云修改信息
        RCUtils.rcUpdate(user.getUserId(),
                StringUtils.hasText(user.getName()) ? user.getName() : u.getName(),
                StringUtils.hasText(user.getPhoto()) ? user.getPhoto() : u.getPhoto());
        updateUser(user);

        return user;
    }

    /**
     * 新建账户 将账户和用户绑定
     * @param uid
     * @param account
     */
    @Override
    public void addAccount(String uid, String account) throws NoSuchDataException {
        // 判断用户在数据库是否存在
        User user = findByUserId(uid);
        if (user == null) throw new NoSuchDataException(ErrorCode.ERR_USER_NOT_EXIST);
// TODO
//        user.setAccount(account);
        userMapper.updateByPrimaryKeySelective(user);
    }

    /**
     * 按user id 获取用户信息
     * @param uid
     * @return
     */
    @Override
    public User findByUserId(String uid) {
        return userMapper.findByUserId(uid);
    }


    @Override
    public UserAuth findUserInfoByPC(String uid) {
        User user = userMapper.findByUserId(uid);
        if (user!=null){
            UserAuth userAuth = new UserAuth();
            userAuth.setUser(user);
            userAuth.setTiao(worksService.findWorksNumByUserId(uid));
            WxBinding wb = wxBindingMapper.findByUserId(uid);
            if (wb!=null){
                userAuth.setWxBdType(1);        //绑定了微信
            }else{
                userAuth.setWxBdType(0);        //没有绑定
            }
            AccountDetail ad = accountDetailMapper.findByUserId(user.getUserId());
            if (ad!=null){
                userAuth.setCertStatus(ad.getCertStatus());
            }else{
                userAuth.setCertStatus(0);
            }
            return userAuth;
        }
        throw new NoSuchDataException(ErrorCode.ERR_USER_NOT_EXIST);
    }


    @Override
    public User findByTel(String tel) {
        return  userMapper.findByTel(tel);
    }

    /**
     * 按姓名，电话，userId 字符串查找用户（最多10条）
     * @param query 查询字符串
     * @return 用户列表
     */
    @Override
    public List<User> findByQueryString(String query) {
        // 姓名
        // 电话
        // 用户id
        // TODO 个数限制
        // 符合id
        List<User> searchById = userMapper.searchById(query);
        List<User> searchByTel = userMapper.searchByTel(query);
        // 按用户名搜索
        List<User> searchByName = userMapper.searchByName(query);

//        if (query.matches("")) return searchById;
        // 符合电话号
        String telPattern = "^((1[3,5,8][0-9])|(14[5,7])|(17[0,6,7,8])|(19[7]))\\d{8}$";
        if (query.matches(telPattern)) return searchByTel;

        if (searchByTel != null)
            searchById.addAll(searchByTel);
        if (searchByName != null)
            searchById.addAll(searchByName);
        return searchById;
    }

    /*******************************
     *
     * 私有方法
     *
     *******************************/

    /**
     * 更新用户
     */
    private void updateUser(User user) {
        User u = new User();
        u.setId(user.getId());
        u.setName(user.getName());
        u.setSex(user.getSex());
        u.setAge(user.getAge());
        u.setPhoto(user.getPhoto());
        u.setBrief(user.getBrief());
        u.setUpdateTime(new Date());
        u.setCreditPoints(user.getCreditPoints());
        userMapper.updateByPrimaryKeySelective(u);
    }

    private User validateUser(String uid) throws GivenNullParamException, NoSuchDataException {
        if (!StringUtils.hasText(uid)) throw new GivenNullParamException();
        User user = findByUserId(uid);
        if (user == null) throw new NoSuchDataException();
        return user;
    }



    @Autowired
    private UserMapper userMapper;

    @Autowired
    private WorksService worksService;

    @Autowired
    private WxBindingMapper wxBindingMapper;

    @Autowired
    private AccountDetailMapper accountDetailMapper;

}
